/*
 * MsgWinHandler.cpp
 *
 *  Created on: 2012-12-18
 *      Author: yangentao@gmail.com
 */

#include <WindowsX.h>
#include "HWNDHandler.h"
#include "StreamLog.h"

namespace yet {

static const int MYMSG_ID = WM_APP + 1;

HWNDHandler::HWNDHandler() {
	w = 0;
	preProc = 0;
}

HWNDHandler::~HWNDHandler() {
	if (w) {
		quit();
	}
}

bool HWNDHandler::onStart() {
	HINSTANCE inst = GetModuleHandleA(0);
	w = CreateWindowEx(0, L"Message", L"", 0, 0, 0, 0, 0, 0, 0, inst, 0);
	if (w) {
		SetProp(w, L"M", this);
		preProc = SubclassWindow(w, MsgWndProc);
	}
	return w != 0;
}
void HWNDHandler::onQuit() {
	if (w) {
		DestroyWindow(w);
		w = 0;
	}

}

void HWNDHandler::notify() {
	if( ! PostMessage(w, MYMSG_ID, 0, 0)){
		slog<<err<<"HWNDHandler::notify failed!"<<endln;
	}
}

LRESULT CALLBACK MsgWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	HWNDHandler* pThis = (HWNDHandler*) GetProp(hWnd, L"M");
	assert(pThis);
	assert(pThis->preProc);
	if (uMsg == MYMSG_ID) {
		pThis->peekAndProcess();
		return 0;
	}
	return CallWindowProc(pThis->preProc, hWnd, uMsg, wParam, lParam);
}

} /* namespace yet */
